﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

[assembly: WebResource("EnhancedWebControls.ClientScripts.DropDownBehavior.js", "text/javascript")]
namespace EnhancedWebControls
{
    [ToolboxData("<{0}:EnhancedDropDown runat=server></{0}:EnhancedDropDown>"),
    DefaultEvent("SelectedIndexChanged"), ControlValuePropertyAttribute("SelectedValue"), ParseChildren(true, "Items")]
    public class EnhancedDropDown : LabeledInput
    {
        #region Events
        public event EventHandler SelectedIndexChanged;
        private void RightDropDown_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            OnSelectedIndexChanged(this, e);
        }
        protected virtual void OnSelectedIndexChanged(object sender, System.EventArgs e)
        {
            if (ScriptManager.GetCurrent(this.Page).IsInAsyncPostBack)
                _returnFocus = true;
            if (SelectedIndexChanged != null)
                SelectedIndexChanged(this, e);
        }
        #endregion

        #region Child Controls
        private DropDownList _rightDropDown; 
        #endregion

        #region Private Storage
        private string _cachedSelectedValue;
        private bool _returnFocus;
        #endregion

        #region Exposed Child Properties
        public string DefaultRowText {
            get
            {
                return (string)ViewState["DefaultRowText"];
            }
            set
            {
                ViewState["DefaultRowText"] = value;
            }
        }
        public string DefaultRowValue { 
            get
            {
                return (string)ViewState["DefaultRowValue"];
            }
            set
            {
                ViewState["DefaultRowValue"] = value;
            }
        }
        public bool ShowDefaultValueInLabelMode { get; set; }
        public object DataSource
        {
            get 
            {
                EnsureChildControls();
                return _rightDropDown.DataSource;
            }
            set 
            {
                EnsureChildControls();
                _rightDropDown.DataSource = value;
            }
        }
        public string DataTextField
        {
            get 
            {
                EnsureChildControls();
                return _rightDropDown.DataTextField;
            }
            set 
            {
                EnsureChildControls();
                _rightDropDown.DataTextField = value;
            }
        }
        public string DataValueField
        {
            get 
            {
                EnsureChildControls();
                return _rightDropDown.DataValueField;
            }
            set 
            {
                EnsureChildControls();
                _rightDropDown.DataValueField = value;
            }
        }
        public string SelectedValue
        {
            get 
            {
                EnsureChildControls();
                if (_rightDropDown.Items.Count == 0)
                    return _cachedSelectedValue;
                else
                    return _rightDropDown.SelectedValue;
            }
            set 
            {
                EnsureChildControls();
                if (_rightDropDown.Items.FindByValue(value) != null)
                    _rightDropDown.SelectedValue = value;
                else
                    _cachedSelectedValue = value;
            }
        }
        public int SelectedIndex
        {
            get 
            {
                EnsureChildControls();
                return _rightDropDown.SelectedIndex;
            }
            set 
            {
                EnsureChildControls();
                _rightDropDown.SelectedIndex = value;
            }
        }
        public bool AutoPostBack
        {
            get 
            {
                EnsureChildControls();
                return _rightDropDown.AutoPostBack;
            }
            set 
            {
                EnsureChildControls();
                _rightDropDown.AutoPostBack = value;
            }
        }
        public bool UseBrowserStyleOnDropDown { get; set; }
        public string DropDownBorder { get; set; }
        public string DropDownActiveBorder { get; set; }
        public string DropDownErrorBorder { get; set; }
        [PersistenceMode(PersistenceMode.InnerDefaultProperty), ]
        public ListItemCollection Items
        {
            get
            {
                EnsureChildControls();
                return _rightDropDown.Items;
            }
        }
        public string DropDownClientID
        {
            get 
            {
                EnsureChildControls();
                return _rightDropDown.ClientID;
            }
        }
        public string DropDownUniqueID
        {
            get 
            {
                EnsureChildControls();
                return _rightDropDown.UniqueID;
            }
        }
        public System.Web.UI.WebControls.ListItem SelectedItem
        {
            get 
            {
                EnsureChildControls();
                return _rightDropDown.SelectedItem;
            }
        }
        public System.Web.UI.AttributeCollection DropDownAttributes
        {
            get 
            {
                EnsureChildControls();
                return _rightDropDown.Attributes;
            }
        }
        public override string ToolTip
        {
            get 
            {
                EnsureChildControls();
                return base.ToolTip;
            }
            set 
            {
                EnsureChildControls();
                base.ToolTip = value;
                _rightDropDown.ToolTip = value;
            }
        }
        #endregion

        #region Overriden Methods
        public EnhancedDropDown()
            : base()
        {
            _returnFocus = false;
            ShowDefaultValueInLabelMode = false;
            DropDownBorder = "1px Solid #828282";
            DropDownActiveBorder = "1px Solid #000000";
            DropDownErrorBorder = "1px Solid #aa0000";
        }
        public override void DataBind()
        {
            EnsureChildControls();
            //if ((!string.IsNullOrEmpty(_rightDropDown.SelectedValue)) && (_rightDropDown.SelectedValue != _cachedSelectedValue))
            //    _cachedSelectedValue = _rightDropDown.SelectedValue;
            if (_rightDropDown.Items.Count > 0 && _rightDropDown.SelectedIndex >= 0)
                _cachedSelectedValue = _rightDropDown.SelectedValue;
            _rightDropDown.Items.Clear();
            _rightDropDown.ClearSelection();
            _rightDropDown.SelectedValue = null;
            _rightDropDown.DataBind();
            if (DefaultRowText != null || DefaultRowValue != null)
                _rightDropDown.Items.Insert(0,new ListItem(DefaultRowText,DefaultRowValue));
            if ((!string.IsNullOrEmpty(_cachedSelectedValue)) && (_rightDropDown.Items.FindByValue(_cachedSelectedValue) != null))
                SelectedValue = _cachedSelectedValue;
        }
        protected override void CreateChildControls()
        {
            Controls.Clear();
            base.CreateChildControls();
            _rightDropDown = new DropDownList();
            _rightDropDown.ID = "RightDropDown";
            _rightDropDown.SelectedIndexChanged += new EventHandler(RightDropDown_SelectedIndexChanged);
            Controls.Add(_rightDropDown);
            _leftLabel.AssociatedControlID = _rightDropDown.ID;
        }
        protected override void OnPreRender(System.EventArgs e)
        {
            EnsureChildControls();
            base.OnPreRender(e);
            if (Visible && !LabelMode && Enabled)
            {
                ScriptManager.RegisterClientScriptResource(this, this.GetType(), "EnhancedWebControls.ClientScripts.DropDownBehavior.js");
                SetDropDownClientScripts();
                if (_returnFocus)
                    Page.SetFocus(_rightDropDown.ClientID);
            }
        }
        protected override void Render(HtmlTextWriter writer)
        {
            EnsureChildControls();
            RenderDesignTimeStyles(writer);
            RenderContainerBegin(writer, true);
            RenderLeftSide(writer);
            RenderRightContainerBegin(writer);

            if (LabelMode)
            {
                _rightLabel.CssClass = "EWC__LabelMode";
                if (_rightDropDown.SelectedItem != null)
                    _rightLabel.Text = _rightDropDown.SelectedItem.Text;
                if (!ShowDefaultValueInLabelMode)
                {
                    if (DefaultRowValue == SelectedValue || String.IsNullOrEmpty(SelectedValue))
                        _rightLabel.Text = null;
                }
                _rightLabel.RenderControl(writer);
                _rightDropDown.Style["display"] = "none";
            }

            if (!UseBrowserStyleOnDropDown)
            {
                _rightDropDown.Style["Padding"] = "2px 2px 2px 0px";
                if (ErrorMode)
                    _rightDropDown.Style["Border"] = DropDownErrorBorder;
                else
                    _rightDropDown.Style["Border"] = DropDownBorder;
                _rightDropDown.Style["Height"] = "24px";
                _rightDropDown.Style["width"] = FieldWidth.ToString();
                if (!Page.Request.Browser.IsBrowserIE())
                    _rightDropDown.CssClass = "EWC_DropDown";
            }
            else
            {
                _rightDropDown.Style["width"] = FieldWidth.ToString();
                _rightDropDown.CssClass = "EWC_DropDown";
            }
            _rightDropDown.RenderControl(writer);

            RenderRightContainerEnd(writer);
            RenderContainerEnd(writer);
        }
        #endregion

        #region Helper Methods
        public void ClearSelection()
        {
            EnsureChildControls();
            _rightDropDown.ClearSelection();
            _rightDropDown.SelectedIndex = -1;
            SelectedValue = null;
        }
        public void SetDefaultRow(string Text, string Value)
        {
            EnsureChildControls();
            if (!string.IsNullOrEmpty(DefaultRowText))
            {
                ListItem defaultRow = _rightDropDown.Items.FindByValue(DefaultRowValue);
                if (defaultRow != null && defaultRow.Text == DefaultRowText)
                    Items.Remove(defaultRow);
            }
            DefaultRowText = Text;
            DefaultRowValue = Value;
            _rightDropDown.Items.Insert(0, new ListItem(DefaultRowText, DefaultRowValue));
            SelectedValue = DefaultRowValue;
        }
        protected void SetDropDownClientScripts()
        {
            string labelClass = "EWC__Label";
            string ddBorder = DropDownBorder;
            if (ErrorMode)
            {
                labelClass = "EWC__ErrorLabel";
                ddBorder = DropDownErrorBorder;
            }
            if (UseBrowserStyleOnDropDown)
            {
                _rightDropDown.Attributes.Add("onblur", "document.getElementById('" + _leftLabel.ClientID + "').className= '" + labelClass + "';");
                _rightDropDown.Attributes.Add("onfocus", "document.getElementById('" + _leftLabel.ClientID + "').className= 'EWC__ActiveLabel';");
            }
            else
            {
                _rightDropDown.Attributes.Add("onblur", "ChangeDropDownField(this, '" + ddBorder + "','" + _leftLabel.ClientID + "', '" + labelClass + "');");
                _rightDropDown.Attributes.Add("onfocus", "ChangeDropDownField(this, '" + DropDownActiveBorder + "','" + _leftLabel.ClientID + "', 'EWC__ActiveLabel')");
            }
        }
        #endregion
    }
}